import {
  Breadcrumb,
  Button,
  Card,
  Radio,
  Form,
  DatePicker,
  Table,
  Space,
  Tag,
  message,
  Modal,
} from 'antd';
import {
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import React, { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom';

import { getArticleAPI, getArticleDeleteAPI } from 'api/article';

import errorSrc from 'assets/error.png';
import Channel from 'component/Channel';

const { RangePicker } = DatePicker;

export default function ArticleList(props) {
  const [articleDate, setArticleDate] = useState({});
  // 缓存数据
  // 解决筛选之后，总条数问题
  const formDataRef = useRef(null);
  // 解决筛选显示当前页数/每页显示条数问题
  const pageInfoRef = useRef(null);
  // 状态
  const articleStatus = [
    { id: -1, name: '全部', color: 'magenta' },
    { id: 0, name: '草稿', color: 'orange' },
    { id: 1, name: '待审核', color: 'red' },
    { id: 2, name: '审核通过', color: 'green' },
    { id: 3, name: '审核失败', color: 'cyan' },
  ];

  const getArticleDate = async (params = {}) => {
    const res = await getArticleAPI(params);
    setArticleDate(res.data);
    // console.log(res);
  };

  useEffect(() => {
    getArticleDate();
  }, []);

  // 筛选
  const handleSubmit = (values) => {
    // console.log(values);
    const formData = { ...values };
    if (values.status === -1) {
      // 删除对象的某个键
      delete formData.status;
    }
    // 拿到后台需要的时间
    if (values.date) {
      // .format 格式化日期
      // startOf('day') 00:00:00 --- (二十四小时置制) 12:00:00 --- (十二小时制)
      const startTime = values.date[0]
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss');
      // endOf('day') 23:59:59 --- (二十四小时置制) 11:59:59 --- (十二小时制)
      const endTime = values.date[1].endOf('day').format('YYYY-MM-DD HH:mm:ss');
      // console.log(startTime, endTime);
      formData.begin_pubdate = startTime;
      formData.end_pubdate = endTime;
      // console.log(formData);
      delete formData.date;
    }
    formDataRef.current = formData;
    getArticleDate(formData);
  };
  // 删除文章
  const handleDelArticleById = (id) => {
    // console.log(id);
    // 二次询问用户
    Modal.confirm({
      title: '温馨提醒！！！',
      icon: <ExclamationCircleOutlined />,
      content: '你确定要删除吗？',
      okText: '确认',
      cancelText: '取消',
      // 点击确认的回调
      // 这里需要注意，异步关闭问题
      onOk: async () => {
        await getArticleDeleteAPI(id);
        message.success('删除成功');
        // 重新渲染数据
        getArticleDate({
          ...(formDataRef.current || {}),
          ...(pageInfoRef.current || {}),
        });
      },
    });
  };

  const columns = [
    // title --- 表格头
    // dadaIndex --- 要显示内容
    // key --- 代表唯一
    // render --- 自定义（有三个参数） render:(text, record, index){} 分别表示字段(name)，当前行数据，索引
    {
      title: '封面',
      dataIndex: 'cover',
      key: 'images',
      render: (value) => {
        if (!value.images.length) {
          return <img width={100} src={errorSrc} alt="" />;
        }
        return <img width={100} src={value.images[0]} alt="" />;
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (value) => {
        const info = articleStatus.find((item) => item.id === value);
        return <Tag color={info.color}>{info.name}</Tag>;
      },
    },
    {
      title: '发布时间',
      key: 'pubdate',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      key: 'read_count',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      key: 'comment_count',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      key: 'like_count',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record, index) => {
        return (
          // Space --- 设置组件之间的间距
          <Space>
            <Button
              type="primary"
              icon={<EditOutlined />}
              shape="circle"
              onClick={() => props.history.push('/edit/' + record.id)}
            ></Button>
            <Button
              danger
              icon={<DeleteOutlined />}
              shape="circle"
              onClick={() => handleDelArticleById(record.id)}
            ></Button>
          </Space>
        );
      },
    },
  ];
  // const data = [];
  return (
    <div style={{ paddingTop: 24 }}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>文章列表</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          autoComplete="off"
          onFinish={handleSubmit}
          initialValues={{ status: -1, channel_id: 0 }}
        >
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="频道" name="channel_id">
            <Channel style={{ width: 200 }}></Channel>
          </Form.Item>

          <Form.Item label="日期" name="date">
            <RangePicker />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
        根据筛选条件共查询到{articleDate.total_count}条数据
        <Table
          columns={columns}
          dataSource={articleDate.results}
          rowKey="id"
          pagination={{
            position: ['bottomCenter'],
            current: articleDate.page,
            pageSize: articleDate.per_page,
            total: articleDate.total_count,
            onChange: (page, pageSize) => {
              // console.log(page, pageSize);
              // console.log(formDataRef);
              pageInfoRef.current = { page, per_page: pageSize };
              getArticleDate({
                page,
                per_page: pageSize,
                ...(formDataRef.current || {}),
              });
            },
          }}
        />
      </Card>
    </div>
  );
}
